Decisions and Loops

Control structures
Not always do you want to perform a sequential set of statements. In order to control when the statements perform, control structures are used.
Conditional statement:
if … else
Selection statement:
switch …
Iterative statements:
for, continue, break
while and do …. While
goto statement

The flow of control
If a program has three parts, called Start, Middle, and End, the flow of control could look like:

Branching statement
Example (Step 1)

Branching statement
Example (Step 2)

Branching statement
Example (Step 3)

Branching statement
Example (Step 4)

if … else

if … else
Variations

if … else
An example

Nesting control statement
Example (Step 1)

Nesting control statement
Example (Step 2)

Nesting control statement
Example (Step 3)

Nesting control statement
Example (Step 4)

if … else
Pascal C/C++
if x < 0 then
  x := -x

switch

Switch
Example

switch
Importance of break

switch
Importance of break

switch
Pascal C/C++
case i of
1: write(‘one’);
2: write(‘two’);
3: write(‘three’);
4: begin
write(‘four’);
i := 3
    end
otherwise
write(‘Bad value’)
end;

switch (Cont.)
Pascal C/C++
case i of
0: write(‘ZeroOne’);
1: write(‘One’)
end;

Loop (while)
Example (Step 1)

Loop (while)
Example (Step 2)

Loop (while)
Example (Step 3)

Loop (while)
Example (Step 4)

while

do … while

while and do …. while
Pascal C/C++
while x < y do
x := 2 * x

Loop (for)
Example (Step 1)

Loop (for)
Example (Step 2)

Loop (for)
Example (Step 3)

Loop (for)
Example (Step 4)

for

for
Pascal C/C++
for i := 1 to n do
x[i] := 0

break, continue
C provides two commands to control how we loop:
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.

break
Pascal C/C++
if, while, repeat, for, or case
  begin
     …
     …
     goto 1
     …
  end;
1:

break (Cont.)
Pascal C/C++
 while, repeat,  or for
  begin
     …
     …
     goto 1
     …
1:
  end;

return
Pascal C/C++
procedure p …
….
goto 1;
…
1:
   end

return (Cont.)
Pascal C/C++
function f …
….
f := somevalue;
     goto 1;
…
1:
   end

The goto statement
goto statement unconditionally transfers control to the statement with the given label.
A label is an identifier followed by a colon:
goto label;
label: do something;

goto
Pascal C/C++
goto 1;
…
1: …

Debugging and breakpoints

Control structures
Things to remember
Use = for assignment, == for comparisons
Logical && and || are short circuits
Use break to implement multiple exits from loops
For each case in a switch statement, there should be a break statement unless required otherwise.